package ink.xiaobaibai.util;

import org.apache.commons.lang3.time.StopWatch;

import java.util.concurrent.TimeUnit;

/**
 * @description: 计时测试类
 * @author: 小白白
 * @create: 2021-06-08
 **/

public class TimingTest {

    private static ThreadLocal<StopWatch> watchThreadLocal = new ThreadLocal<>();

    /**
     * 开始计时
     */
    public static void start() {
        StopWatch stopWatch = new StopWatch();
        watchThreadLocal.set(stopWatch);
        stopWatch.start();
    }

    /**
     * 获取时间
     */
    public static void printAndRemove() {
        StopWatch stopWatch = watchThreadLocal.get();
        if (stopWatch == null) {
            throw new RuntimeException("请先开启计时");
        }
        stopWatch.stop();
        long time = stopWatch.getTime(TimeUnit.MILLISECONDS);
        System.out.println("花费时间:" + time + "毫秒");
        watchThreadLocal.remove();
    }

}
